import json
from model.config_reader import ConfigReader


class ServerManager:
    """全局服务器状态管理器（单例）"""

    def __init__(self):
        self.selected_servers = set()       # 勾选状态
        self.server_connections = {}        # 连接状态
        self.config_reader = ConfigReader()
        self.devices = json.loads(self.config_reader.get_value("devices", "Lava", ""))

        self._server_cache = self._load_servers()

    def _load_servers(self):
        """格式化返回服务器信息"""
        try:
            return [
                {
                    'ip': d.get('ip', ''),
                    'username': d.get('username', ''),
                    'password': d.get('password', ''),
                    'connected': False,
                    'station': d.get('name', 'Unknown'),
                }
                for d in self.devices
            ]
        except Exception:
            return []

    # ---------------- 状态更新 ----------------
    def toggle_server(self, ip: str, checked: bool):
        """更新服务器勾选状态"""
        if checked:
            self.selected_servers.add(ip)
        else:
            self.selected_servers.discard(ip)

    def select_all_servers(self):
        for s in self._server_cache:
            self.selected_servers.add(s['ip'])

    def deselect_all_servers(self):
        self.selected_servers.clear()

    def update_connection_status(self, ip: str, connected: bool):
        """更新服务器连接状态"""
        self.server_connections[ip] = connected

    # ---------------- 状态查询 ----------------
    def get_all_servers(self):
        """返回所有服务器的完整信息"""
        return self._server_cache

    def get_selected_servers(self):
        """返回当前勾选的服务器信息"""
        return [
            s for s in self._server_cache
            if s['ip'] in self.selected_servers
        ]
    def get_connected_servers(self):
        """返回当前已连接服务器 IP"""
        return [
            s for s in self._server_cache
            if s['ip'] in self.selected_servers and self.server_connections.get(s['ip'], False)
        ]
